#include "listnode.h"

/*
https://leetcode.cn/problems/merge-k-sorted-lists
*/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
    if (!list1)
    {
        return list2;
    }
    if (!list2)
    {
        return list1;
    }
    struct ListNode* head = NULL;
    struct ListNode* tail = NULL;

    while (list1 && list2)
    {
        if (list1->val < list2->val)
        {
            if (!head)
            {
                head = tail = malloc(sizeof(struct ListNode));
                tail->val = list1->val;
                list1 = list1->next;
                tail->next = NULL;
            }
            else
            {
                tail->next = list1;
                list1 = list1->next;
                tail = tail->next;
                tail->next = NULL;
            }
        }

        else
        {
            if (!head)
            {
                head = tail = malloc(sizeof(struct ListNode));
                tail->val = list2->val;
                list2 = list2->next;
                tail->next = NULL;
            }
            else
            {
                tail->next = list2;
                list2 = list2->next;
                tail = tail->next;
                tail->next = NULL;
            }
        }
    }

    if (list1)
    {
        tail->next = list1;
    }

    if (list2)
    {
        tail->next = list2;
    }

    return head;
}

struct ListNode* mergeKLists(struct ListNode** lists, int listsSize)
{
    if (!listsSize || !lists)
    {
        return NULL;
    }
    struct ListNode* res = NULL;

    for (int i = 0; i < listsSize; i++)
    {
        res = mergeTwoLists(res, lists[i]);
    }
    return res;
}